package com.wxmp.config;

import com.google.common.collect.Maps;
import com.wxmp.wxcms.domain.Account;
import com.wxmp.wxcms.service.AccountService;

import lombok.AllArgsConstructor;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.constant.WxMpEventConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * wechat mp configuration
 *
 * @author Binary Wang(https://github.com/binarywang)
 */
@AllArgsConstructor
@Configuration
public class WxMpConfiguration {
	@Autowired
	private AccountService entityService;
	
    @Bean
    public WxMpService wxMpService() {
        // 代码里 getConfigs()处报错的同学，请注意仔细阅读项目说明，你的IDE需要引入lombok插件！！！！
    	final List<Account> listAccount = entityService.listForPage(new Account());
    	System.out.println(listAccount+"----------------");
        if (listAccount == null) {
            throw new RuntimeException("大哥，拜托先看下项目首页的说明（readme文件），添加下相关配置，注意别配错了！");
        }

        WxMpService service = new WxMpServiceImpl();
        service.setMultiConfigStorages(listAccount
            .stream().map(a -> {
                WxMpInMemoryConfigStorage configStorage = new WxMpInMemoryConfigStorage();
                configStorage.setAppId(a.getAppid());
                configStorage.setSecret(a.getAppsecret());
                configStorage.setToken(a.getToken());
                return configStorage;
            }).collect(Collectors.toMap(WxMpInMemoryConfigStorage::getAppId, a -> a, (o, n) -> o)));
        return service;
    }

}
